﻿var status = require('http-status');

var jwt = require('jsonwebtoken');

var User = require('../models/user');
var options = require('../options');

var express = require('express');
var router = express.Router();

router.post('/login', function (req, res) {
    var username = req.body.username;
    var password = req.body.password;
    if (!username || !password) {
        return res.status(status.BAD_REQUEST).json({error: "No Username or Password Provided"});
    }
    User.findOne({username: username}, "+password", function (err, user) {
        if (err) {
            return res.status(status.INTERNAL_SERVER_ERROR).end();
        }
        if (!user) {
            return res.status(status.NOT_FOUND).json({error: "User Not Found"});
        }

        user.verifyPassword(password, function (err, isMatch) {
            if (err) {
                return res.status(status.INTERNAL_SERVER_ERROR).end();
            }
            if (!isMatch) {
                return res.status(status.BAD_REQUEST).json({error: "Wrong Password"});
            }
            var token = jwt.sign({id: user._id, username: user.username}, options.jwtSecret, {expiresIn: "1h"});
            res.json({token: token});
        });
    });
});

router.post('/logout', function (req, res) {
    return res.status(status.OK).end();
});


module.exports = router;